<!DOCTYPE html>
<html>
<head>
  <link rel="chrome-webstore-item">
</head>
<body>
<script>
  console.log('Page loaded');

  function runTest(galleryUrl, index) {
    var storeUrl = galleryUrl + '/detail/ecglahbcnmdpdciemllbhojghbkagdje';
    // Link URL has to be generated dynamically in order to include the right
    // port number. The ID corresponds to the data in the "extension" directory.
    document.getElementsByTagName('link')[0].href = storeUrl;

    function shouldPass(func) {
      return {
        func: func,
        shouldPass: true
      }
    }

    function shouldFail(func) {
      return {
        func: func,
        shouldPass: false
      }
    }

    var cwi = chrome.webstore.install;
    var callback = function() {
    };

    var testCases = [
      shouldPass(function() {cwi()}),
      shouldPass(function() {cwi(undefined)}),
      shouldPass(function() {cwi(undefined, undefined)}),
      shouldPass(function() {cwi(undefined, undefined, undefined)}),

      shouldPass(function() {cwi(storeUrl)}),
      shouldPass(function() {cwi(undefined, callback)}),
      shouldPass(function() {cwi(undefined, undefined, callback)}),
      shouldPass(function() {cwi(undefined, callback, callback)}),

      shouldFail(function() {cwi(callback)}),
      shouldFail(function() {cwi(callback, callback)}),
      shouldFail(function() {cwi(callback, callback, callback)}),

      shouldFail(function() {cwi(123)}),
      shouldFail(function() {cwi(undefined, 123)}),
      shouldFail(function() {cwi(undefined, undefined, 123)}),
      shouldFail(function() {cwi(undefined, callback, 123)})
    ];

    var successResult = (index < testCases.length - 1 ? 'KEEPGOING' : 'DONE');
    var failureResult = 'FAILED';

    function runTestCase(test) {
      var failed = false;
      console.log('Testing ' + test.func);
      if (test.shouldPass) {
        try {
          test.func();
        } catch (e) {
          console.log('unexpected exception: ' + e);
          failed = true;
        }
      } else {
        try {
          test.func();
          console.log('unexpected pass: ' + func);
          failed = true;
        } catch (e) {
          // Expected exception
        }
      }

      console.log('Ran test, sending response');
      window.domAutomationController.send(failed ? failureResult : successResult);
      console.log('Test complete');
    }

    runTestCase(testCases[index]);
  }
</script>

</body>
</html>
